const fs = require("node:fs");
const ejs = require("ejs");
const { marked } = require("marked");
const browserSync = require("browser-sync");
let browser = null;

// 读取模板，并将 markdown 转换为 html
function convert(callback) {
  // 获取 markdown
  const mdStr = fs.readFileSync("README.md", "utf8");
  ejs.renderFile(
    "template.ejs",
    {
      title: "markdown to html",
      content: marked(mdStr),
    },
    (err, str) => {
      if (err) {
        throw err;
      }
      console.log(str);
      // 写入 index.html
      fs.writeFileSync("index.html", str, "utf8");

      // 执行回调函数
      callback && callback();
    }
  );
}
// 开启服务
function startServe() {
  browser = browserSync.create();
  browser.init({
    server: {
      baseDir: "./",
      index: "index.html",
    },
  });
}

convert(startServe);

fs.watchFile("README.md", (curr, prev) => {
  if (curr.mtime !== prev.mtime) convert(() => browser.reload());
});
